/**
 * @desc：关联订单号弹窗
 * @author:binlety
 *
 *
 * * */
import React, { useState, useEffect } from 'react';
import { Button, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import CommonModal from '@/components/CommonModal'
import CommonTable from '@/components/CommonTable'
import CommonLoading from '@/components/CommonLoading'
import { getRelativeOrderSnOp } from '../../../service'
import { formatAmount, cpText } from '@/utils/utils.jsx';
import { uniqBy } from 'lodash';

export default ({ visible, record, handleClose }) => {
  const [loading, setLoading] = useState(false);//loading
  const [data, setData] = useState([]);//表格数据
	const navigate = useNavigate();

	//1是老用户，2是新用户
	const isNewUser = localStorage.getItem('isOldSystemUser') == 2 ? true : false;

	const orderPath = isNewUser ? '/views/order/list' : '/trade/orderhandle';
  useEffect(()=>{
    if(visible){
       getRelativeOrderSn();//获取关联订单号
    }
  },[visible])

  //获取关联订单号
  const getRelativeOrderSn = async () => {
    setLoading(true)
    setData([])
    const { success, data } = await getRelativeOrderSnOp({payOrderSn:record.payOrderSn})
    if(success){
      setData(data)
    }
    setLoading(false)
  }

  //渲染跳转去页面去订单处理页面的span
  const renderJumptOrderHandle = (orderSn, state) => {
    return <span className='common-color1' style={{cursor:'pointer'}} onClick={()=>publicHandleClick(orderPath, orderSn, state)}>{orderSn}</span>
  }

  //公共跳转逻辑
  const publicHandleClick = (pathname, orderSn, erpOrderSrc) => {
    onCancel()
    let timer = setTimeout(() => {
      clearTimeout(timer);
      timer = null;
      navigate(pathname,{ state: {orderSn, erpOrderSrc }});
    },200)
  }

  const columns = [
    {
      title: "唯一码",
      dataIndex: "uniqueCode",
      key: "uniqueCode",
      width: 100,
      render: (text, r) => {
        if(r.amount == 0) {
          return text;
        }
        return (
          <span 
            className='common-color1' 
            style={{cursor:'pointer'}} 
            onClick={() => 
            publicHandleClick(
              r.amount < 0 ? '/views/purchase/FmcmPurchase' : '/views/afterSales/FmcmReturns', 
              text
            )}
          >
            {text}
          </span>
        )
      }
    },
    {
      title: "商品名称",
      dataIndex: "goodsName",
      key: "goodsName",
      width: 180,
      render: (text, { goodsName, goodsSpec, goodsCode }) => (
        <>
          <div>商品名称：{goodsName}</div>
          <div>规格型号：{goodsSpec}</div>
          <div>商品编码：{goodsCode}</div>
        </>
      )
    },
    {
      title: "数量",
      dataIndex: "num",
      key: "num",
      width: 80,
    },
    {
      title:"变动金额",
      dataIndex:"amount",
      key:"amount",
      width: 100,
      render:(text) => {
        if(text){
          if(text.toString().includes('-')){
            return <span className='common-color10'>{formatAmount(text)}</span>
          }else{
            return <span className='common-color9'>+{formatAmount(text)}</span>
          }
        }else{
          return '0.00'
        }
      }
    },
    {
      title:"业务订单号",
      dataIndex:"orderSn",
      key:"orderSn",
      width: 160,
      render:(text, { orderSrc, spd, state }) =>{
        const { transType, tradeNo }  = record
        const noJumptarr = [1, 2, 3, 7, 10, 11, 14, 15, 16, 17, 18 ],
              jumptOrderHandleArr = [6, 8, 12, 13, 21, 22, 23, 25, 27, 33, 34, 35, 37, 39, 40, 43]
        if(noJumptarr.includes(transType)){
          return <span>{text}</span>
        } else if(tradeNo.startsWith('S')) {
            return renderJumptOrderHandle(text, state);
        }
        else if(jumptOrderHandleArr.includes(transType)){//订单反审核
          return renderJumptOrderHandle(text, state)
        }else if(transType == 4){//下单付款 订单处理-全部
        //   if(orderSrc == 'ERP'){//erp订单 自发订单 已发货
        //     if(spd) {
        //       // return renderJumptOrderHandle(text)
        //       return <span className='common-color1' style={{cursor:'pointer'}} onClick={()=>publicHandleClick('/views/order/list', text)}>{text}</span>
        //     }else {
        //       return renderJumptOrderHandle(text, state)
        //     }
        //   }else{//商城订单
        //     return <span>{text}</span>
        //   }
          return renderJumptOrderHandle(text, state)
          // return <span>{text}</span>
        }else if(transType == 5){//运费差价
          if(spd){//自发订单 自发订单 已发货
            return <span className='common-color1' style={{cursor:'pointer'}} onClick={()=>publicHandleClick('/views/order/list', text)}>{text}</span>
          }else{//代发订单 订单处理-全部
             return renderJumptOrderHandle(text, state)
          }
        }else if(transType == 9){//订单退款
          return <span className='common-color1' style={{cursor:'pointer'}} onClick={()=>publicHandleClick('/views/afterSales/salesOrder', text, record.orderSrc)}>{text}</span>
        } else if (transType == 28 || transType == 29 || transType == 30) { //采购订单
          if(transType == 28 && tradeNo.startsWith('T')){
            return text;
          }else{
            if(text.startsWith('M')) {
                return <span className='common-color1' style={{cursor:'pointer'}} onClick={()=> { navigate(
                    `/views/order/list?orderSn=${text}`)}
                  }>{text}</span>
            } else {
                return <span className='common-color1' style={{cursor:'pointer'}} onClick={()=> {navigate("/views/purchase/PurchaseOrder?purchaseOrderNos=" + text);onCancel()}
                }>{text}</span>
            }
          }
        } else{
          return <span>{text}</span>
        }
      }
    },
  ]

  const hasNum = data.some(item => item.num > 0);

  //表格
  const TableProps = {
    data,
    columns: hasNum ? columns : columns.filter(item => item.key == 'orderSn' || item.key == 'amount').reverse(),
  }

  //关闭操作
  const onCancel = () => {
    // setData([]) //加上展示效果不好，明显有等待时长
    handleClose()
  }

  const handleFormatAndCopy = (fieldName) => {
    if(data.length > 200){
      message.info('限定最多只能复制200条');
    }
    const copyText = uniqBy(data, fieldName).map((item) => item[fieldName]).slice(0, 200).join(',');
    cpText(copyText);
  }

  return <CommonModal
    title="关联订单号"
    visible={visible}
    width='600px'
    onCancel={onCancel}
    footer={[
      <Button key='copyCode' type='primary' shape='round' onClick={() => handleFormatAndCopy('uniqueCode')}>复制唯一码</Button>,
      <Button onClick={() => handleFormatAndCopy('orderSn')} key='copy' type='primary' shape='round'>复制业务订单号</Button>,
      <Button onClick={onCancel} key='close'>关闭</Button>
    ]}
  >
    <CommonTable { ...TableProps }/>
    <CommonLoading loading={loading}/>
  </CommonModal>
}